#pragma once

#include <iostream>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>

namespace hladdr
{
    class InetAddr
    {
    public:
        InetAddr() {}
        InetAddr(std::string ip, uint16_t port)
            : _ip(ip), _port(port)
        {
            _addr.sin_family = AF_INET;
            inet_aton(_ip.c_str(), &_addr.sin_addr);
            _addr.sin_port = htons(_port);
        }
        InetAddr(struct sockaddr_in addr) : _addr(addr)
        {
            _ip = inet_ntoa(_addr.sin_addr);
            _port = ntohs(addr.sin_port);
        }
        InetAddr(uint16_t port) : _ip("0"), _port(port)
        {
            _addr.sin_family = AF_INET;
            _addr.sin_addr.s_addr = INADDR_ANY;
            _addr.sin_port = htons(_port);
        }
        struct sockaddr *GetInetAddr() { return (struct sockaddr *)&_addr; }
        std::string GetIP() { return _ip; }
        uint16_t GetPort() { return _port; }
        socklen_t GetLen() { return sizeof(_addr); }
        bool operator==(InetAddr &addr) { return _ip == addr._ip && _port == addr._port; }
        std::string ToString() { return _ip + "-" + std::to_string(_port); }
        void Set(std::string ip, uint16_t port)
        {
            _ip = ip;
            _port = port;
            _addr.sin_family = AF_INET;
            inet_aton(_ip.c_str(), &_addr.sin_addr);
            _addr.sin_port = htons(_port);
        }

    private:
        struct sockaddr_in _addr;
        std::string _ip;
        uint16_t _port;
    };
}